.PHONY: all

TARGET_CC := ${TC_PREFIX}gcc

TARGET_LD ?= ${TC_PREFIX}ld
TARGET_OBJDUMP ?= ${TC_PREFIX}objdump
TARGET_OBJCOPY ?= ${TC_PREFIX}objcopy
TARGET_NM ?= ${TC_PREFIX}nm
LN ?= ln

MAKE ?= make
RM ?= rm

FIND ?= /usr/bin/find
ECHO ?= echo

CCFLAGS	:= -gstabs -I../inc/ -I../lib/ -nostdlib -nostdinc -fno-builtin 

LIBGCC	:= $(shell ${TARGET_CC} -print-libgcc-file-name)

SRCFILES:= $(shell ${FIND} . -iname "*.c" -or -iname "*.S" | sed -e 's!\./!!g')
OBJFILES:= $(addprefix ../target/kern_,\
		     $(addsuffix .o,$(foreach FILE,${SRCFILES},$(shell echo ${FILE} | sed -e 's!_!_1!g' -e 's!/!_2!g'))))
DEPFILES:= $(OBJFILES:.o=.d)

all: ../target/kernel ../target/kernel.sym ../target/kernel.asm

-include $(DEPFILES)

../target/kern_%.d:
	@${ECHO} DEP $(shell echo $* | sed -e 's!_1!_!g' -e 's!_2!/!g')
	${V}${TARGET_CC} -MM $(CCFLAGS) $(shell echo $* | sed -e 's!_1!_!g' -e 's!_2!/!g') -MT $(@:.d=.o) > $@
	${V}echo "$(@:.d=.o): $(shell echo $* | sed -e 's!_1!_!g' -e 's!_2!/!g')" >> $@

../target/kern_%.o: ../target/kern_%.d
	@${ECHO} CC $(shell echo $* | sed -e 's!_1!_!g' -e 's!_2!/!g')
	${V}${TARGET_CC} $(CCFLAGS) $(shell echo $* | sed -e 's!_1!_!g' -e 's!_2!/!g') -c -o $@

../target/kernel: ${OBJFILES}
	@${ECHO} LD $@
	${V}${TARGET_LD} -N -T kernel.ld -o$@ ../target/lib_*.o ${OBJFILES} ${LIBGCC}

../target/kernel.sym: ../target/kernel
	${V}${TARGET_NM} $< | grep -i " t " | sed "s/ [tT] / /g" > $@

../target/kernel.asm: ../target/kernel
	${V}${TARGET_OBJDUMP} -S $< > $@

